<template>
    <div>
    
     <el-row>
        <el-col :span="10"><div class="grid-content ep-bg-purple-dark" />
        <ul>
        <li v-for="i in mlist" :key="i.id">
            {{i}}       
        </li>       
        </ul>
        </el-col>     
     </el-row>

     <button @click="sendMessage">Send Message</button>
    
    </div>
    </template>
    
    <script setup>
    import {ref, onMounted}  from 'vue'
    
    //搜索用的
    const socket = ref(null)
    const mlist=ref([{"id":1,"name":"张三"},{"id":2,"name":"李四"}])
    
    
    const initwesockt=()=>{
        socket.value = new WebSocket("ws://localhost:8000/room/22");
    
        // 当客户端和服务端刚创建好连接(self.accept)之后，自动触发.
        socket.value.onopen =  (event)=>{
            console.log("连接成功")
        }
    
        // 回调函数，客户端接收服务端消息
        socket.value.onmessage =  (event)=>{
            console.log(event.data);
                    
            // var data  = JSON.parse(event.data)
            // mlist.value.push(data)
            mlist.value.push(event.data)
        }
    
        // // 当断开连接时，触发该函数
        // this.socket.onclose =function (event){
        // let tag = document.createElement("div");
        // tag.innerText = "[连接断开]";
        // document.getElementById("message").appendChild(tag);
        // }
    }

    // 发送消息
    const sendMessage = () => {
      if (socket.value.readyState === WebSocket.OPEN) {
        const message = "Hello from Vue!";
        socket.value.send(message);
        console.log('Message sent:', message);
      } else {
        console.error('WebSocket connection is not open');
      }
    }
    
    onMounted(() => {
        initwesockt()
    })
    </script>
    